package binarytree

func levelOrder(root *TreeNode) [][]int {
	res := [][]int{}
	if root == nil {
		return res
	}
	q := []*TreeNode{root}

	for len(q) > 0 {
		levelVal := []int{}
		levelLen := len(q)
		for j := 0; j < levelLen; j++ {
			levelVal = append(levelVal, q[j].Val)
			if q[j].Left != nil {
				q = append(q, q[j].Left)
			}
			if q[j].Right != nil {
				q = append(q, q[j].Right)
			}
		}
		res = append(res, levelVal)
		q = q[levelLen:]
	}

	return res
}
